/**
 * An Application
 * 
 * @author Nont Banditwongo
 * 
 * @copyright (c) 2008, opencare.org
 * @date 15. April 2008
 * @version 0.5
 * 
 * @license application.js is licensed under the terms of the Open Source LGPL
 *          3.0 license. Commercial use is permitted to the extent that the
 *          code/component(s) do NOT become part of another Open Source or
 *          Commercially licensed development library or toolkit without
 *          explicit permission.
 * 
 * License details: http://www.gnu.org/licenses/lgpl.html
 */

/* global Ext, Application */

// reference local blank image
Ext.BLANK_IMAGE_URL = 'ext/resources/images/default/s.gif';

// create namespace
Ext.namespace('opencare');

// application main entry point
Ext.onReady(function() {

	Ext.QuickTips.init();

	// detail window
	var localEventWin;
	var globalEventWin;

	
	var localEventReader = new Ext.data.JsonReader({
		totalProperty : "totalSize",
		root : "data"
	}, Ext.data.Record.create([{
		name : "id",
		type : "string"
	}, {
		name : "topic",
		type : "string"
	}, {
		name : "description",
		type : "string"
	}, {
		name : "mapPath",
		type : "string"
	}, {
		name : "eventType",
		type : "string"
	}, {
		name : "level",
		type : "string"
	}, {
		name : "disasterType",
		type : "string"
	}, {
		name : "dateCreated",
		type : "string"
	}]));
	
	var localEventStore = new Ext.data.Store({
		proxy : new Ext.ux.data.DWRProxy({
			dwrFunction : EventManager.findPagingEventMap,
			listeners : {
				'beforeload' : function(dataProxy, params) {
					params[dataProxy.loadArgsKey] = [params.start, params.limit];
				}
			}
		}),
		reader : localEventReader
	});

	var localEventColumns = [{
		"header" : "ID",
		"dataIndex" : "id",
		"sortable" : "true",
		"id" : "id",
		"width" : 200
	}, {
		"header" : "Topic",
		"dataIndex" : "topic",
		"sortable" : "true",
		"id" : "topic",
		"width" : 200
	}, {
		"header" : "Event Type",
		"dataIndex" : "eventType",
		"sortable" : "true",
		"id" : "eventType"
	}, {
		"header" : "Disaster Type",
		"dataIndex" : "disasterType",
		"sortable" : "true",
		"id" : "disasterType"
	}, {
		"header" : "Level",
		"dataIndex" : "level",
		"sortable" : "true",
		"id" : "level"
	}, {
		"header" : "Created",
		"dataIndex" : "dateCreated",
		"sortable" : "true",
		"id" : "dateCreated",
		"width" : 200
	}];
	
	var globalEventReader = new Ext.data.JsonReader({
		totalProperty : "totalSize",
		root : "data"
	}, Ext.data.Record.create([{
		name : "id",
		type : "string"
	}, {
		name : "sender",
		type : "string"
	}, {
		name : "topic",
		type : "string"
	}, {
		name : "description",
		type : "string"
	}, {
		name : "category",
		type : "string"
	}, {
		name : "event",
		type : "string"
	}, {
		name : "urgency",
		type : "string"
	}, {
		name : "certainty",
		type : "string"
	}, {
		name : "severity",
		type : "string"
	}, {
		name : "language",
		type : "string"
	}, {
		name : "mapPath",
		type : "string"
	}, {
		name : "pubDate",
		type : "string"
	}, {
		name : "createdDate",
		type : "string"
	}, {
		name : "alertLevel",
		type : "string"
	}]));
				
	var globalEventStore = new Ext.data.Store({
		proxy : new Ext.ux.data.DWRProxy({
			dwrFunction : EventManager.findPagingGlobalEventMap,
			listeners : {
				'beforeload' : function(dataProxy, params) {
					params[dataProxy.loadArgsKey] = [params.start, params.limit];
				}
			}
		}),
		reader : globalEventReader
	});
		
	var globalEventColumns = [{
		"header" : "ID",
		"dataIndex" : "id",
		"sortable" : "true",
		"id" : "id",
		"width" : 200
	}, {
		"header" : "Alert Level",
		"dataIndex" : "alertLevel",
		"sortable" : "true",
		"id" : "alertLevel",
		"width" : 200
	}, {
		"header" : "Sender",
		"dataIndex" : "sender",
		"sortable" : "true",
		"id" : "topic",
		"width" : 200
	}, {
		"header" : "Topic",
		"dataIndex" : "topic",
		"sortable" : "true",
		"id" : "topic",
		"width" : 200
	}, {
		"header" : "Event Type",
		"dataIndex" : "event",
		"sortable" : "true",
		"id" : "event",
		"width" : 150
	}, {
		"header" : "Public Date",
		"dataIndex" : "pubDate",
		"sortable" : "true",
		"id" : "pubDate",
		"width" : 200
	}];

	// create the Grid
	var localEventGrid = new Ext.grid.GridPanel({
		store : localEventStore,
		columns : localEventColumns,
		autoHeight : true,
		stripeRows : true,
		loadMask : true,
		viewConfig : {
			forceFit : true,
			enableRowBody : true,
			showPreview : true,
			getRowClass : function(record, rowIndex, p, store) {
				if (this.showPreview) {
					p.body = '<p>' + record.data.excerpt + '</p>';
					return 'x-grid3-row-expanded';
				}
				return 'x-grid3-row-collapsed';
			}
		},
		bbar : new Ext.PagingToolbar({
			pageSize : 15,
			store : localEventStore,
			displayInfo : true,
			displayMsg : 'Displaying topics {0} - {1} of {2}',
			emptyMsg : "No topics to display",
			items : ['-', {
				pressed : true,
				enableToggle : true,
				text : 'Show Preview',
				cls : 'x-btn-text-icon details',
				toggleHandler : localEventToggleDetails
			}]
		})
	});

	// create the Grid
	var globalEventGrid = new Ext.grid.GridPanel({
		store : globalEventStore,
		columns : globalEventColumns,
		autoHeight : true,
		stripeRows : true,
		loadMask : true,
		viewConfig : {
			forceFit : true,
			enableRowBody : true,
			showPreview : true,
			getRowClass : function(record, rowIndex, p, store) {
				if (this.showPreview) {
					p.body = '<p>' + record.data.excerpt + '</p>';
					return 'x-grid3-row-expanded';
				}
				return 'x-grid3-row-collapsed';
			}
		},
		bbar : new Ext.PagingToolbar({
			pageSize : 15,
			store : globalEventStore,
			displayInfo : true,
			displayMsg : 'Displaying topics {0} - {1} of {2}',
			emptyMsg : "No topics to display",
			items : ['-', {
				pressed : true,
				enableToggle : true,
				text : 'Show Preview',
				cls : 'x-btn-text-icon details',
				toggleHandler : globalEventToggleDetails
			}]
		})
	});
	
	// trigger the data store load
	localEventStore.load({
		params : {
			start : 0,
			limit : 15
		}
	});

	globalEventStore.load({
		params : {
			start : 0,
			limit : 15
		}
	});
	
	
	
	function localEventToggleDetails(btn, pressed) {
		var view = grid.getView();
		view.showPreview = pressed;
		view.refresh();
	}
	
	function globalEventToggleDetails(btn, pressed) {
		var view = globalEventGrid.getView();
		view.showPreview = pressed;
		view.refresh();
	}
	
	var eventLevelReader = new Ext.data.JsonReader({
		totalProperty : "totalSize",
		root : "data"
	}, Ext.data.Record.create([{
		name : "id",
		type : "string"
	}, {
		name : "level",
		type : "string"
	}]));

	var eventLevelStore = new Ext.data.Store({
		proxy : new Ext.ux.data.DWRProxy({
			dwrFunction : EventManager.findAllEventLevelMap,
			listeners : {
				'beforeload' : function(dataProxy, params) {
					params[dataProxy.loadArgsKey] = [];
				}
			}
		}),
		reader : eventLevelReader
	});

	var disasterTypeReader = new Ext.data.JsonReader({
		totalProperty : "totalSize",
		root : "data"
	}, Ext.data.Record.create([{
		name : "id",
		type : "string"
	}, {
		name : "type",
		type : "string"
	}]));

	var disasterTypeStore = new Ext.data.Store({
		proxy : new Ext.ux.data.DWRProxy({
			dwrFunction : EventManager.findAllDisasterTypeMap,
			listeners : {
				'beforeload' : function(dataProxy, params) {
					params[dataProxy.loadArgsKey] = [];
				}
			}
		}),
		reader : disasterTypeReader
	});

	var eventTypeReader = new Ext.data.JsonReader({
		totalProperty : "totalSize",
		root : "data"
	}, Ext.data.Record.create([{
		name : "id",
		type : "string"
	}, {
		name : "type",
		type : "string"
	}]));

	var eventTypeStore = new Ext.data.Store({
		proxy : new Ext.ux.data.DWRProxy({
			dwrFunction : EventManager.findAllEventTypeMap,
			listeners : {
				'beforeload' : function(dataProxy, params) {
					params[dataProxy.loadArgsKey] = [];
				}
			}
		}),
		reader : eventTypeReader
	});

	var eventForm = new Ext.FormPanel({
		id : 'eventForm',
		labelWidth : 80, // label settings here cascade unless overridden
		url : 'upload.form',
		frame : true,
		bodyStyle : 'padding:5px 5px 0',
		autoWidth : true,
		defaultType : 'textfield',
		fileUpload : true,
		items : [{
			xtype : 'textfield',
			fieldLabel : 'Map',
			name : 'file',
			inputType : 'file'
		}, {
			xtype : 'textfield',
			fieldLabel : 'Topic',
			name : 'topic',
			width : 200,
			allowBlank : false
		}, {
			xtype : 'textarea',
			fieldLabel : 'Description',
			name : 'description',
			width : 200,
			allowBlank : false
		}, {
			xtype : 'combo',
			name : 'levels',
			fieldLabel : 'Level',
			store : eventLevelStore,
			displayField : 'level',
			valueField : 'id',
			hiddenName : 'levelsId',
			typeAhead : true,
			mode : 'local',
			triggerAction : 'all',
			selectOnFocus : true,
			allowBlank : false,
			emptyText : 'Select a level...'
		}, {
			xtype : 'combo',
			name : 'dTypes',
			fieldLabel : 'Disaster Type',
			store : disasterTypeStore,
			displayField : 'type',
			valueField : 'id',
			hiddenName : 'dTypesId',
			typeAhead : true,
			mode : 'local',
			triggerAction : 'all',
			selectOnFocus : true,
			allowBlank : false,
			emptyText : 'Select a type...'
		}, {
			xtype : 'combo',
			name : 'eTypes',
			fieldLabel : 'Event Type',
			store : eventTypeStore,
			displayField : 'type',
			valueField : 'id',
			hiddenName : 'eTypesId',
			typeAhead : true,
			mode : 'local',
			triggerAction : 'all',
			selectOnFocus : true,
			allowBlank : false,
			emptyText : 'Select a type...'
		}, {
			xtype : "fieldset",
			title : "Options",
			autoWidth : true,
			autoHeight : true,
			items : [{
				xtype : "textfield",
				fieldLabel : "Latitude",
				name : "latitude",
				id : "latitude"
			}, {
				xtype : "textfield",
				fieldLabel : "Longitude",
				name : "longitude",
				id : "longitude"
			}]
		},{
			xtype : 'checkbox',
			fieldLabel : 'Public',
			name : 'isPublic',
			id : "isPublic"
		}],

		buttons : [{
			text : 'Save',
			formBind : true,
			handler : function() {
				if (eventForm.form.isValid()) {

					Ext.MessageBox.show({
						title : 'Please wait...',
						msg : 'Processing ...',
						width : 240,
						progress : false,
						closable : false
					});

					eventForm.form.submit({

						success : function(form, result) {
							Ext.MessageBox.hide();
							Ext.Msg.alert('Status',
									'Changes applied successfully.');
							localEventStore.load({
								params : {
									start : 0,
									limit : 15
								}
							});
							eventForm.form.reset();

							console.info(Ext
									.decode(result.response.responseText));

						}
					});
				} else {
					Ext.Msg.alert("Error", "Invalid form fields");
				}
			}
		}, {
			text : 'Cancel',
			formBind : true,
			handler : function() {
				eventForm.form.reset();
			}
		}]
	});

	// Main layout
	var viewport = new Ext.Viewport({
		layout : 'border',
		items : [{
			region : "north",
			height : 70,
			border : false,
			html: '<table cellpadding="5" border="0" width="100%"><tr><td><img src="img/ndwc_logo.gif"></td><td><img src="img/opencare_logo.jpg" align="right"></td></tr><tr><td colspan="2" align="right"><a href="/ocweb/logout">Sign out</a></td></tr></table>'
		}, {
			region : 'south',
			split : true,
			height : 50,
			minSize : 50,
			maxSize : 200,
			collapsible : true,
			title : 'Info',
			margins : '0 0 0 0'			
		}, {
			region : 'west',
			id : 'west-panel',
			split : true,
			title : 'Event Reporter',
			width : 310,
			autoScroll : true,
			collapsible : true,
			items : [{
				layout : "anchor",
				border : false,
				items : [eventForm]
			}]
		}, {
			region : 'center',
			id : 'center-panel',
			useShim : true,
			layout : 'fit',
			split : false,
			border : false,
			items : [{
				xtype : "tabpanel",
				activeTab : 0,
				width : '100%',
				frame : true,
				layoutOnTabChange: true,//do a layout of tab items as tabs are changed
				items : [{
					xtype : "panel",
					title : "Local Event",
					items : [localEventGrid]
				}, {
					xtype : "panel",
					title : "Global Event",
					items : [globalEventGrid]
					//html : [globalEventGrid]
				}]
			}]
		}]
	});
	
	localEventGrid.getSelectionModel().selectFirstRow();
	
	var globalEventTab = Ext.getCmp('center-panel').getComponent(0);
	globalEventTab.setActiveTab(1);	
	
	globalEventGrid.getSelectionModel().selectFirstRow();
	
	globalEventTab.setActiveTab(0);
	
	
	localEventGrid.getView().getRowClass = function(record, index) {
		if (record.data.level == 'ADVISORY')
			return 'green-row';
		else if (record.data.level == 'WATCH')
			return 'orange-row';
		else if (record.data.level == 'WARNING')
			return 'red-row';
		else if (record.data.level == 'TERMINATION')
			return 'grey-row';
	};
	
	globalEventGrid.getView().getRowClass = function(record, index) {
		if (record.data.alertLevel == 'ADVISORY')
			return 'green-row';
		else if (record.data.alertLevel == 'WATCH')
			return 'orange-row';
		else if (record.data.alertLevel == 'WARNING')
			return 'red-row';
		else if (record.data.alertLevel == 'TERMINATION')
			return 'grey-row';
	};
	
	function localEventHandleRowSelect(selectionModel, rowIndex, selectedRecord) {
		// assuming the record has a field named 'url' or build it as you need
		// to
		var id = selectedRecord.get('id');
		var topic = selectedRecord.get('topic');
		var description = selectedRecord.get('description');
		var mapPath = selectedRecord.get('mapPath');

		// if you want to open another window

		var detail_tab = new Ext.Panel({
			title : topic,
			html : topic
		});

		// create the window on the first click and reuse on subsequent clicks
		if (!localEventWin) {
			localEventWin = new Ext.Window({
				layout : 'fit',
				width : 500,
				height : 500,
				closeAction : 'hide',
				title : 'Event',
				plain : true,
				items : {
					id : 'event_win_tabpanel',
					xtype : 'tabpanel',
					activeTab : 0,
					border : false,
					items : [{
						title : 'Detail',
						autoScroll : true,
						html : "Event detail"
					}, {
						title : 'Map',
						autoScroll : true,
						html : 'Disaster Map'
					}]
				},

				buttons : [{
					text : 'Submit',
					disabled : true
				}, {
					text : 'Close',
					handler : function() {
						localEventWin.hide();
					}
				}]
			});
		}

		localEventWin.show(this);

		var tabs = localEventWin.getComponent(0);
		tabs.setActiveTab(0);
		tabs.getComponent(0).body.update(description);
		tabs.getComponent(0).setTitle(topic);

		tabs.setActiveTab(1);
		tabs.getComponent(1).body.update("<img src=\"http://mail.opencare.org/ndwc.maps/"
				+ mapPath + "\">");

		tabs.setActiveTab(0);

	}
	
	localEventGrid.getSelectionModel().on('rowselect', localEventHandleRowSelect);

	
	function globalEventHandleRowSelect(selectionModel, rowIndex, selectedRecord) {
		// assuming the record has a field named 'url' or build it as you need
		// to
		var id = selectedRecord.get('id');
		var topic = selectedRecord.get('topic');
		var description = selectedRecord.get('description');
		var mapPath = selectedRecord.get('mapPath');

		// if you want to open another window

		var detail_tab = new Ext.Panel({
			title : topic,
			html : topic
		});

		// create the window on the first click and reuse on subsequent clicks
		if (!globalEventWin) {
			globalEventWin = new Ext.Window({
				layout : 'fit',
				width : 500,
				height : 500,
				closeAction : 'hide',
				title : 'Event',
				plain : true,
				items : {
					id : 'event_win_tabpanel',
					xtype : 'tabpanel',
					activeTab : 0,
					border : false,
					items : [{
						title : 'Detail',
						autoScroll : true,
						html : "Event detail"
					}, {
						title : 'Map',
						autoScroll : true,
						html : 'Disaster Map'
					}]
				},

				buttons : [{
					text : 'Submit',
					disabled : true
				}, {
					text : 'Close',
					handler : function() {
						globalEventWin.hide();
					}
				}]
			});
		}

		globalEventWin.show(this);

		var tabs = globalEventWin.getComponent(0);
		tabs.setActiveTab(0);
		tabs.getComponent(0).body.update(description);
		tabs.getComponent(0).setTitle(topic);

		tabs.setActiveTab(1);
		tabs.getComponent(1).body.update("<img src=\""+ mapPath + "\">");

		tabs.setActiveTab(0);

	}
	
	globalEventGrid.getSelectionModel().on('rowselect', globalEventHandleRowSelect);
	// load data into the store
	eventLevelStore.load();
	eventTypeStore.load();
	disasterTypeStore.load();
	// store.load();

	// enable form monitoring
	eventForm.startMonitoring();
	
		var localEventRefresh = {
		run : function() {
			localEventStore.load({
				params : {
					start : 0,
					limit : 15
				}
			});
		},
		interval : 60000
			// 30 second
	}
	
	var globalEventRefresh = {
		run : function() {
			globalEventStore.load({
				params : {
					start : 0,
					limit : 15
				}
			});
		},
		interval : 6000
			// 30 second
	}
		
	Ext.TaskMgr.start(localEventRefresh);
	Ext.TaskMgr.start(globalEventRefresh);
	
}); // eo function onReady

// eof
